 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
 <%@ include file="/WEB-INF/component/commonTagLib.jsp"%>
<!DOCTYPE html>
<html>
<head>
	<title><spring:message code="message.lable.GouWuJiHuaChaKan"/></title>
	<%@ include file="/WEB-INF/component/commonCSS.jsp"%>
    <!--[if lt IE 9]>
        <script src="lib/js/html5shiv.min.js"></script>
        <script src="lib/js/respond.min.js"></script>
    <![endif]-->
</head>
<body class="skin-blue sidebar-mini fixed skin-blue-light-frame">
    <section class="content-header">
        <h1><spring:message code="message.list.WoDeGouWuChe"/></h1>
        <ol class="breadcrumb">
        	<li><a href="${ctx}/home.jsp"><i class="fa fa-home"></i><spring:message code="message.lable.first"/></a></li>
        	<li><a href="#">交易</a></li>
			<li><a href="#"><spring:message code="message.list.DingDanGuanLi"/></a></li>
            <li class="active"><a href="#"><spring:message code="message.list.WoDeGouWuChe"/></a></li>
        </ol>
    </section>

	<section class="content">     
	<div class=" box box-success">
	<div class="box-body">
                <div class="input">
                    <div class="textalign1"><spring:message code="message.listForm.tongYongMing"/><spring:message code="message.yanZheng.maoHao"/></div>
                    <div class="boxinput">
                        <input type="text" class="textinput" id="drugName" name="drugName" placeholder="<spring:message code="message.listForm.tongYongMing"/>/<spring:message code="message.listForm.pinYinMa"/>" />
                    </div>
                   <div class="textalign1"><spring:message code="message.listForm.shengChanQiYe"/><spring:message code="message.yanZheng.maoHao"/></div>
                    <div class="boxinput">
                        <input type="text" class="textinput" id="compName" name="compName" placeholder="<spring:message code="message.listForm.shengChanQiYe"/>/<spring:message code="message.listForm.pinYinMa"/>" />
                    </div>
					<div class="textalign1">药品来源<spring:message code="message.yanZheng.maoHao"/></div>
                        <div class="boxinput">
                        <select class="textinput"  id="goodsSource" name="goodsSource">
                        <option value=""><spring:message code="message.select.option"/></option>
                        <c:forEach items="${list }" var="list">
                            <option value="${list.dicCode }">${list.dicName }</option>
                        </c:forEach>
                        </select>
                    </div>
					<div class="textalign1" >
						<button type="button" onclick="gridSerch();" class="btn btn-success btn-sm" id="selectDicCompType"><spring:message code="message.button.seachSpacing"/></button>
					</div> 
                 </div>
				 <div class="input" style="margin-top:3px;display:none;">
					<div class="textalign1" >
						<button type="button" onclick="gridSerch();" class="btn btn-success btn-sm" id="selectDicCompType"><spring:message code="message.button.seachSpacing"/></button>
					</div> 	
				</div>
            </div>
	</div>
        <table class="jqgrid" id="gridlist"></table>
        <div id="gridpage"></div>
        <div class=" box box-warning bottongroup">
	        <label id="batchModifyData" onclick="batchModifyData()" class="btn btn-primary btn-sm"><spring:message code="message.button.saveSpacing"/></label>
            <button type="button" onclick="createOrder();" class="btn btn-primary btn-sm"><spring:message code="message.button.ShengChengDingDan"/></button>
            <button type="button" onclick="removeDel();" class="btn btn-danger btn-sm"><spring:message code="message.button.delete"/></button>
        </div>
        
        
        
        
        
        
        
        
    </section>
    <%@ include file="/WEB-INF/component/commonJS.jsp"%>
    <script type="text/javascript">
  //绑定回车
    $('#projId,#drugCode,#drugName,#compName,#userName,#isLongTimePlan').bind('keydown', function(event) {
        if (event.keyCode == "13") {
            $('#selectDicCompType').click();
        }
    });	
    $("#drugName").focus();//加载页面光标在第一个查询框内
        $(function () {
        	$("#projId").HNSelect({
                url: "${pageContext.request.contextPath}/selectController/getMyProj.html", data: { ID: '' },  defaultText: "<option value=''><spring:message code="message.select.option"/></option>",
            });
        	$("#drugForm1").HNSelect({
                url: "${pageContext.request.contextPath}/selectController/getForm.html", data: { ID: '0' },  defaultText: "<option value=''><spring:message code="message.select.option"/></option>",
                func: function () {
                    $("#drugForm2").HNSelect({
                        parent_selector: "#drugForm1", url: "${pageContext.request.contextPath}/selectController/getForm.html", dataid: "ID",  defaultText: "<option value=''><spring:message code="message.select.option"/></option>",
                    });
                }
            });
            $("#gridlist").jqGrid({
                url: "${ctx}/purPurPlanController/getPurPlanDataList.html",
                mtype: "POST",
                datatype: "json",
                autowidth: true,
                shrinkToFit: false,
             //   height: 260,
                colNames: [
                           'prodCompId',
                           'cartId',
                           'hospId',
                           '<spring:message code="message.listForm.CaiGouXianJia"/>',
                           '<spring:message code="message.listForm.CaiGouJia"/>',
                           '<spring:message code="message.listForm.CaiGouShuLiang"/>',
                           '<spring:message code="message.listForm.CaiGouJinE"/>',
                           '<spring:message code="message.listForm.PeiSongQiYe"/>',
                           '<spring:message code="message.listForm.yaoPinBianMa"/>',
                           '<spring:message code="message.listForm.tongYongMing"/>', 
                           '<spring:message code="message.listForm.jiXing"/>',
                           '<spring:message code="message.listForm.guiGe"/>',
                           '<spring:message code="message.listForm.zhuanHuanXiShu"/>',
                           '<spring:message code="message.listForm.baoZhuangDanWei"/>', 
                           '<spring:message code="message.listForm.caiZhi"/>',
                           '<spring:message code="message.listForm.shengChanQiYe"/>',
                           '国药准字',
                           '<spring:message code="message.listForm.shangBianMa"/>',
						   '商品来源',
                           '<spring:message code="message.listForm.XiangMuMingCheng"/>',
                           '<spring:message code="message.listForm.JiaRuJiHuaShiJian"/>',
                           '<spring:message code="message.button.JiaRuJiHuaRen"/>',
                           '<spring:message code="message.listForm.IsorNoBeiAn"/>'
                           
                           ],
                colModel: [
					{ name: 'prodCompId',index:'n1', width:60, hidden:true,align:"center", sortable:false  },
					{ name: 'cartId', index: 'ship',hidden:true, width: 50,align:"right",sortable:false},
					{ name: 'hospId', index: 'ship',hidden:true, width: 50,align:"right",sortable:false},
					{ name: 'proLimitPrice', index: 'ship', hidden:true,width: 80,align:"right",sortable:false},
					{ name: 'proPrice', index: 'ship', width: 80,align:"right",sortable:false},
					{ name: 'buyNum', index: 'ship', width: 80, align: "right",sortable:false },
					{ name: 'proMoney', index: 'ship', width: 80, align: "right",sortable:false},
					{ name: 'delComp', index: 'ship', width: 140, align: "center",sortable:false},
					{ name: 'drugCode', index: 'sdate', hidden:true,width: 100, align: "center",sortable:false},
                    { name: 'drugName', index: 'name', width: 130, align: "left" ,sortable:false },
                    { name: 'formName', index: 'stock', width: 80 , align: "center",sortable:false},
                    { name: 'specName', index: 'ship', width: 80, align: "center" ,sortable:false},
                    { name: 'factor', index: 'ship', width: 80, align: "center" ,sortable:false},
                    { name: 'unit', index: 'ship', width: 80, align: "center" ,sortable:false},
                    { name: 'materialName', index: 'ship', hidden:true,width: 80, align: "center" ,sortable:false},
                    { name: 'compName', index: 'ship', width: 160, align: "left",sortable:false},
                	{ name: 'drugMedicine',width: 100, align: "center", sortable:false},
                    { name: 'goodsCode', index: 'sdate', width: 100, align: "center",sortable:false,hidden:true},
					{ name: 'goodsSource', index: 'ship',width: 80,align:"center",sortable:false},
                    { name: 'projectName', index: 'sdate', width: 160, align: "center",sortable:false},
                    { name: 'joinPlanTime', index: 'sdate', hidden:true,width: 140, align: "center",sortable:false},
                    { name: 'joinPlanUser', index: 'sdate', hidden:true,width: 160, align: "center",sortable:false},
                    { name: 'lsBackDrugFlag',inde:'status',hidden:true, width : 80, align : 'center', sortable:false }
                ],
                rowNum: -1,
                //rowList: [10, 20, 50, 100],
                rownumbers: true,
                //pager: "#gridpage",
                multiselect: true, 
                viewrecords: true,
                gridComplete: function(a, b, c){
                	//序号列宽度自适应（参数为jqgridID）
                    autoRNWidth("gridlist");
                	//数据只有一条时默认选中（参数为jqgridID）
                   selectByOneData("gridlist");
            		var ids = jQuery("#gridlist").jqGrid('getDataIDs');
            		for(var i=0;i < ids.length;i++){
            			var id = ids[i];
            			var rowdata = $("#gridlist").jqGrid('getRowData', id);
            			var proMoney = rowdata.proPrice * 10000 * rowdata.buyNum / 10000;
            			a = "<input class=\"\" style=\"width:75px;text-align: right;\" type=\"text\" name=\"buyNum\" id=\"buyNum"+id+"\" onclick=\"selectId("+id+")\" onblur=\"changeAllPrice("+id+");\" value=\""+rowdata.buyNum+"\" />";
            			b="<span id=\"proMoneyId"+id+"\">"+formatAmount(proMoney)+"</span>";
            			c = "<input class=\"\" style=\"width:75px;text-align: right;\" type=\"text\" id=\"proPrice"+id+"\" value=\""+rowdata.proPrice+"\" />";
            			 if ("${isSetPlanPrice}" == "true"){
                      	   if (rowdata.lsBackDrugFlag == "true"){
                      		   a = "<input class=\"\" style=\"width:75px;text-align: right;\" type=\"hidden\" name=\"buyNum\" id=\"buyNum"+id+"\" onclick=\"selectId("+id+")\" onblur=\"changeAllPrice("+id+");\" value=\""+rowdata.buyNum+"\" />"+rowdata.buyNum;
                      		   c = rowdata.proPrice;
                      	   }
                         } else {
                        	 c = rowdata.proPrice;
                        	 if (rowdata.lsBackDrugFlag == "true" && "${bakBatchBuy}" != "true"){
                        		   a = "<input class=\"\" style=\"width:75px;text-align: right;\" type=\"hidden\" name=\"buyNum\" id=\"buyNum"+id+"\" onclick=\"selectId("+id+")\" onblur=\"changeAllPrice("+id+");\" value=\""+rowdata.buyNum+"\" />"+rowdata.buyNum;
                        	   }
                         }
            			 
            			jQuery("#gridlist").jqGrid('setRowData',ids[i],{buyNum:a,proMoney:b,proPrice:c});
            		}	
            		$($("input[name='buyNum']")).keyup(function(event){
                    	  var num =$(this).attr("id").replace(/([^0-9])/ig,'');
                    	  changeSelectChecked("#gridlist",num,$(this).val(),event);
                      }); 
            	},
                caption: "<spring:message code="message.list.proddruginfoStdlist"/>&nbsp;&nbsp;&nbsp;<spring:message code="message.listForm.ZongJinE"/><spring:message code="message.yanZheng.maoHao"/><label id=\"allPrice\">${allPrice}</label>", 
                jsonReader: {
                    repeatitems: false,
                    id: "ids"
                },
                loadComplete: function (data) { //完成服务器请求后，回调函数
                	$("#gridlist").setCaption("<spring:message code='message.list.proddruginfoStdlist'/>&nbsp;&nbsp;&nbsp;<spring:message code='message.listForm.ZongJinE'/><spring:message code='message.yanZheng.maoHao'/><label id=\"allPrice\">"+data.conditions.allPrice+"</label>");
                }
            });
            $("#gridlist").jqGrid('navGrid', '#gridpage', { add: false, edit: false, del: false, search: false, refresh: false });
            $(window).trigger("resize");
            $("#gridlist").jqGrid("setGridHeight", create());
        });
        
      
     //查询
        function gridSerch() {	
        	var projId = $.trim($("#projId").val());
        	var drugCode = $.trim($("#drugCode").val());
        	var drugName = $.trim($("#drugName").val());
        	var compName = $.trim($("#compName").val());
        	var goodsSource = $.trim($("#goodsSource").val());
        	var userName = $.trim($("#userName").val());
        	
    		$("#gridlist").jqGrid('setGridParam',{  
    	        datatype:'json',
    	        postData:{
    	        		"projId":projId,
    	        		"drugCode":drugCode,
    	        		"drugName":drugName,
    	        		"compName":compName,
    	        		"goodsSource":goodsSource,
    	        		"userName":userName},
    	        		page:1
    	    }).trigger("reloadGrid"); //重新载入  
    	}
        //删除
        function removeDel(){
		    var rowIds = $("#gridlist").jqGrid("getGridParam", "selarrrow") || [];
			if (rowIds.length <= 0) {
				$.HN.message.alert("请选择要刪除的药品！", "<spring:message code="message.HN.alert.type"/>", "warn");
				return;
			}
			var drugName ='';
            for (var i=0; i<rowIds.length; i++) {
                rowId = rowIds[i];
                var rowdata = $("#gridlist").jqGrid('getRowData', rowId);
                
                if(i<3){
                	drugName+= rowdata.drugName+"<br/>"
                	if(i==2)
                	drugName+='...';
                	
                }
            }
			$.HN.message.confirm('确定删除以下药品吗？<br/>'+drugName, '', '').on(function (e) {
    			if (e) {
					var list = [];
					for (var i=0; i<rowIds.length; i++) {
						rowId = rowIds[i];
						var rowdata = $("#gridlist").jqGrid('getRowData', rowId);
						list.push({"cartId":rowdata.cartId});
					}
					$.post("${ctx}/purPurPlanController/batchDelete.html", {
						"array" : json.jsonToString(list)
						}, function(result) {
							if (result.success) {
								$.HN.message.alert("刪除成功！", "<spring:message code="message.HN.alert.type"/>", "success");
								gridSerch();
							} else {
								$.HN.message.alert("删除失败！", "<spring:message code="message.HN.alert.type"/>", "error");
							}
						}, "json")
    			}
    		});
		}
        
        //保存
					function batchModifyData() {
        	 			var reg = new RegExp(regexEnum.intege1);
						var rowIds = $("#gridlist").jqGrid("getGridParam", "selarrrow") || [];
						if(rowIds.length <=0){
							$.HN.message.alert("请选择要保存的药品！", "<spring:message code="message.HN.alert.type"/>", "warn");
							return;
						}
						
						var list = [];
						var drugName = '';
			    		for (var i=0; i<rowIds.length; i++) {
			    			rowId = rowIds[i];
			    			var rowdata = $("#gridlist").jqGrid('getRowData', rowId);
			    			var buynum = "";
			    			if (rowdata.lsBackDrugFlag == "true"  && "${bakBatchBuy}" != "true"){
			    				//buynum = rowdata.buyNum;
			    				buynum = $.trim($("#buyNum"+rowId).val());
			    			} else {
			    				buynum = $.trim($("#buyNum"+rowId).val());
			    			}
			    			if ($.trim(buynum).length < 1){
			                    $.HN.message.alert("<spring:message code="message.yanZheng.pleaseTianXieCaiGouShuLiang"/>！", "<spring:message code="message.HN.alert.type"/>", "warn");
			                    return;
			                }
			    			if($.trim(buynum).length > 10){
			                    $.HN.message.alert('<spring:message code="message.yanZheng.CaiGouShuLiangTaiChang"/>', '<spring:message code="message.HN.alert.type"/>', 'warn');
			                     return;
			                } 
			    			
			    			if(!reg.test(buynum)){
			    				$.HN.message.alert("<spring:message code="message.yanZheng.CaiGouShuLiangWeiDaYuLingDeZhengShu"/><spring:message code="message.yanZheng.ganTanHao"/><spring:message code="message.yanZheng.qingChongXinShuRu"/>", "<spring:message code="message.HN.alert.type"/>", "warn");
			    				return;
			    			}
			    			var proprice = "";
			                if ("${isSetPlanPrice}" == "true"){
			                	if (rowdata.lsBackDrugFlag == "true"){
			        				proprice = rowdata.proPrice;
			        			} else {
			        				proprice = $.trim($("#proPrice"+rowId).val());
			        			}
			                } else {
			                	proprice = rowdata.proPrice;
			                }
			                if ($.trim(proprice).length < 1){
			                    $.HN.message.alert("采购价不能为空！", "<spring:message code="message.HN.alert.type"/>", "warn");
			                    return;
			                }
							
							if(i<3){
								drugName+= rowdata.drugName+"<br/>"
								if(i==2)
								drugName+='...';
								
							}
			    			list.push({"cartId":rowdata.cartId,"buyNum":buynum,"proPrice":proprice,"drugName":rowdata.drugName,"proLimitPrice":rowdata.proLimitPrice}); 
			    			
			    		}
			    		$.HN.message.confirm('确定保存以下药品吗？<br/>'+drugName, '', '').on(function (e) {
			    			if (e) {
			    		$.post("${ctx}/purPurPlanController/batchSave.html", {
			    			"array" : json.jsonToString(list)
			    		}, function(result) {
			    			if (result.success) {
			    				var curpage = $("#gridlist").jqGrid('getGridParam', 'page');
			    				gridSerch();
			    				$.HN.message.alert("保存成功！", "<spring:message code="message.HN.alert.type"/>", "success");
	    	    			} else {
	    	    				$.HN.message.alert(result.msg, "<spring:message code="message.HN.alert.type"/>", "error");
			    			}
			    		}, "json").error(function(err) {
			    			top.window.document.location = "${ctx}/login.html"; 
			    		});
			    			}
			    		});
					}
               //生成订单
					 function createOrder(){
						 var reg = new RegExp(regexEnum.intege1);
				        	var rowIds = $("#gridlist").jqGrid("getGridParam", "selarrrow") || [];
				    		if (rowIds.length <= 0) {
				    			$.HN.message.alert("请选择要生成订单的药品！", "<spring:message code="message.HN.alert.type"/>", "warn");
				    			return;
				    		}
				    		var list = [];
				    		for (var i=0; i<rowIds.length; i++) {
				    			rowId = rowIds[i];
				    			 var rowdata = $("#gridlist").jqGrid('getRowData', rowId);
				    			 
				    			 if ($.trim($("#buyNum"+rowId).val()).length < 1){
					                    $.HN.message.alert("<spring:message code="message.yanZheng.pleaseTianXieCaiGouShuLiang"/>！", "<spring:message code="message.HN.alert.type"/>", "warn");
					                    return;
					                }
					    			if($.trim($("#buyNum"+rowId).val()).length > 10){
					                    $.HN.message.alert('<spring:message code="message.yanZheng.CaiGouShuLiangTaiChang"/>', '<spring:message code="message.HN.alert.type"/>', 'warn');
					                     return;
					                } 
				    			 
				    			 if(!reg.test($.trim($("#buyNum"+rowId).val()))){
					    				$.HN.message.alert("<spring:message code="message.yanZheng.CaiGouShuLiangWeiZhengZhengShu"/><spring:message code="message.yanZheng.ganTanHao"/><spring:message code="message.yanZheng.qingChongXinShuRu"/>", "<spring:message code="message.HN.alert.type"/>", "warn");
					    				return;
					    		}
				    			list.push({"cartId":rowdata.cartId, "buyNum":$("#buyNum"+rowId).val(),"proMoney":$("#proMoneyId"+rowId).html(),"goodsSource":rowdata.goodsSource });
				    		}
				    		var isHisRecordAmount = ${isHisRecordAmount};
				    		if(isHisRecordAmount){
				    			$.post("${ctx}/purPurPlanController/getHisRecordAmount.html",{},function(result){
					    			var data = {
					    					"nonEsAmount":0,//页面勾选的非备案药物金额
					    					"esAmount":0,//页面勾选的备案药物金额
					    					"baseAllAmount":0,//备案药物金额
					    					"allAmount":0//药物采购总金额
					    			}
					    			$.each(list,function(i,value){
					    				if(value.goodsSource=="备案采购"){
					    					data.esAmount+=Number(value.proMoney);
					    				}else{
					    					data.nonEsAmount+=Number(value.proMoney);
					    				}
					    			});
					    			data.baseAllAmount = (data.esAmount+ Number(result.rows.base_amount));
					    			data.allAmount = (data.nonEsAmount + data.esAmount + Number(result.rows.non_base_amount) + Number(result.rows.base_amount));
					    			var res =((data.baseAllAmount*10000)/(data.allAmount*10000)); 
					    			console.log(data);
				    				console.log('当前备案采购金额占比： '+res);
					    			if(res>0.02){
							    		$.HN.message.confirm("备案采购金额占比超过<span class = 'red' >2%</span>,是否继续生成订单？", '', '').on(function (e) {
							    			if (e) {
							    				openOrderInfo(list);
							    			}
							    		});
					    			}else{
					    				openOrderInfo(list);
					    			}
					    		},"json");
				    		}else{
				    			openOrderInfo(list);
				    		}
				        }
				       
               
                    function openOrderInfo(list){
                    	$.HN.dialog.open({
				    		id:"selectAddr",
				    		title:"<spring:message code="message.button.TiJiaoDingDan"/>",
				    		url:"${ctx}/createOrder/toCreateOrder.html",
				    		data:{"array": json.jsonToString(list)},
				    		width:"800px",
				    		height:"400px",
				    		closefunc:function(){
				    			gridSerch(); 
				    		}
				    		});
                    }
               
               		function selectId(id){
               			jQuery('#gridlist').jqGrid('setSelection',id);
               		}
               
				     function changeAllPrice(id){
				    		var allPrice = 0;
				    		allPrice = Number(allPrice);
				    		var rowdata = $("#gridlist").jqGrid('getRowData', id);
				    		var price = rowdata.proPrice * 10000 * ($("#buyNum"+id).val())/ 10000;
				    		$("#proMoneyId"+id).html(formatAmount(price))
				    			 
				    		 var obj= $("#gridlist").jqGrid('getRowData');
				    		 for (var i=1 ; i <= obj.length; i++) {
				    			 allPrice +=Number($('#proMoneyId'+i).html());
				    		 }
				    		$("#gridlist").setCaption("<spring:message code='message.list.GouWuJiHuaXiangMuLieBiao'/>&nbsp;&nbsp;&nbsp;<spring:message code='message.listForm.ZongJinE'/><spring:message code='message.yanZheng.maoHao'/>"+formatAmount(allPrice));
				     }  
        
    </script>
</body>
</html>